<?php
class Management extends Controller{
    public $data;

    function __construct(){
        parent::__construct();
        Session::init();
        $this->bar = new Bar();
        $this->model("model_management");
        $this->model("model_website");
    }

    public function index(){
        //Set url begin login
        Session::set("url", "management");
        Session::commit();

        //Bar content
        $bar_content = $this->bar->getBarManagement();
        $this->data['bar_content'] = $bar_content;

        //User
        if (Session::get("uid")){
            $user = $this->model_website->getUsersById(Session::get("uid"));
            $this->data['user'] = $user;
        }

        $this->data['view'] = "management";
        $this->data['type'] = "management";
        $this->data['title'] = "Quản lý";
        $this->data['data'] = "";
        $this->view->render("layout/body", $this->data);
    }

    public function saveCampaign(){
        if(isset($_POST['name'])){
            $uid = Session::get("uid");
            $name = $_POST['name'];
            $url = mb_strtolower($this->libs->url_title($this->libs->removeSign($name)));
            $short_des = $_POST['short_des'];
            $long_des = $_POST['long_des'];
            $type = $_POST['type'];
            $begin = $_POST['begin'];
            $end = $_POST['end'];
            $image = $_POST['image'];

            //Gender
            $criteria_male = $_POST['criteria_male'];
            $c_male = 0;
            if(json_decode($criteria_male)){
                $c_male = 1;
            }
            $criteria_female = $_POST['criteria_female'];
            $c_female = 0;
            if(json_decode($criteria_female)){
                $c_female = 2;
            }

            //Age
            $criteria_14_19 = $_POST['criteria_14_19'];
            $c_14_19 = 0;
            if(json_decode($criteria_14_19)){
                $c_14_19 =  1;
            }
            $criteria_20_29 = $_POST['criteria_20_29'];
            $c_20_29 = 0;
            if(json_decode($criteria_20_29)){
                $c_20_29 = 2;
            }
            $criteria_30_39 = $_POST['criteria_30_39'];
            $c_30_39 = 0;
            if(json_decode($criteria_30_39)){
                $c_30_39 = 4;
            }
            $criteria_40_49 = $_POST['criteria_40_49'];
            $c_40_49 = 0;
            if(json_decode($criteria_40_49)){
                $c_40_49 = 8;
            }
            $criteria_50 = $_POST['criteria_50'];
            $c_50 = 0;
            if(json_decode($criteria_50)){
                $c_50 = 16;
            }

            //Location
            $criteria_province = $_POST['criteria_province'];
            $c_province = 0;
            if(json_decode($criteria_province)){
                $c_province = 1;
            }
            $criteria_hcm = $_POST['criteria_hcm'];
            $c_hcm = 0;
            if(json_decode($criteria_hcm)){
                $c_hcm = 2;
            }
            $criteria_hanoi = $_POST['criteria_hanoi'];
            $c_hanoi = 0;
            if(json_decode($criteria_hanoi)){
                $c_hanoi = 4 ;
            }

            //House size
            $criteria_single = $_POST['criteria_single'];
            $c_single = 0;
            if(json_decode($criteria_single)){
                $c_single = 1;
            }
            $criteria_married = $_POST['criteria_married'];
            $c_married = 0;
            if(json_decode($criteria_married)){
                $c_married = 2;
            }
            $criteria_1_child = $_POST['criteria_1_child'];
            $c_1_child = 0;
            if(json_decode($criteria_1_child)){
                $c_1_child = 4;
            }
            $criteria_2_child = $_POST['criteria_2_child'];
            $c_2_child = 0;
            if(json_decode($criteria_2_child)){
                $c_2_child = 8;
            }

            $gender = $c_male + $c_female;
            $age = $c_14_19 + $c_20_29 + $c_30_39 + $c_40_49 + $c_50;
            $location = $c_province + $c_hcm + $c_hanoi;
            $housesize = $c_single + $c_married + $c_1_child + $c_2_child;

            $date = new DateTime($begin);
            $begin = $date->format('Y-m-d');
            $date = new DateTime($end);
            $end = $date->format('Y-m-d');

            $today = date("Y-m-d H:i:s");
            $cid = $this->model_management->addCampaign($uid, $name, $short_des, $long_des, $url, $today, $begin, $end, $type, $gender, $age, $location, $housesize);
            if($cid){
                //update image cid
                foreach($image as $v){

                    $this->model_management->updateImageCidById($v, $cid);
                }

                echo json_encode(array("status"=>"ok"));
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function getBuzzer(){
        if(isset($_POST['gender'])){
            $gender = $_POST['gender'];
            $begin = $_POST['begin'];
            $end = $_POST['end'];
            $location = $_POST['location'];
            //$criteria = $_POST['criteria'];
            $profile = $_POST['profile'];

            //Gender
            $sqlGender = "";
            if($gender == "1"){
                $sqlGender = " and sex = 1";
            }else if($gender == "2"){
                $sqlGender = " and sex = 2";
            }

            //Age
            $sqlAge = " and DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between ".$begin." and ".$end."";

            //Location
            $sqlLocation = "";
            $number = 0;
            foreach($location as $k=>$v){
                if($v != 0){
                    if($number == 0){
                        $sqlLocation .= "and ( pid = ".$v."";
                    }else{
                        $sqlLocation .= "or pid = ".$v."";
                    }
                }
                $number++;
            }
            if(sizeof($location) > 1){
                $sqlLocation .= ")";
            }

            //Thong tin ca nhan
            $sqlProfile = "";
            if(sizeof($profile) > 0){
                $numberProfile = 0;
                foreach($profile as $k=>$v){
                    if($numberProfile == 0){
                        $sqlProfile = "";
                    }else{

                    }
                }
            }

            //Lam dep
            $sqlBeautiful = "";

            //Ho gia dinh
            $sqlFamily = "";

            //Suc khoe va the thao
            $sqlHealthy = "";

            //Cong viec
            $sqlWorks = "";

            //Mua sam
            $sqlSales = "";

            //Cong nghe
            $sqlTech = "";

            //Thuc an va do uong
            $sqlEat = "";

            //So thich
            $sqlHobby = "";

            $sqlBuzzer = "1=1 ". $sqlGender . $sqlAge . $sqlLocation;

            var_dump($sqlBuzzer);

            $data = $this->model_management->getBuzzer($sqlBuzzer);
            echo json_encode(array("status"=>"ok", 'data'=>$data));

        }else{
            echo json_encode(array("status"=>"error"));
        }

        /*if(isset($_POST['criteria_male'])){
            //Gender
            $sqlGender = "";
            $criteria_male = json_decode($_POST['criteria_male']);
            $criteria_female = json_decode($_POST['criteria_female']);
            if($criteria_male && $criteria_female){
                $sqlGender = "and sex = 1 or sex = 2";
            }else{
                if($criteria_male){
                    $sqlGender = "and sex = 1";
                }else if($criteria_female){
                    $sqlGender = "and sex = 2";
                }
            }

            //Age
            $sqlAge = "";
            $criteria_14_19 = json_decode($_POST['criteria_14_19']);
            $criteria_20_29 = json_decode($_POST['criteria_20_29']);
            $criteria_30_39 = json_decode($_POST['criteria_30_39']);
            $criteria_40_49 = json_decode($_POST['criteria_40_49']);
            $criteria_50 = json_decode($_POST['criteria_50']);
            if($criteria_14_19){
                $sqlAge .= "and DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between 14 and 19";
            }

            if($criteria_20_29){
                if($criteria_14_19){
                    $sqlAge .= "or DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between 19 and 29";
                }else{
                    $sqlAge .= "and DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between 19 and 29";
                }
            }

            if($criteria_30_39){
                if($criteria_14_19 || $criteria_20_29){
                    $sqlAge .= "or DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between 30 and 39";
                }else{
                    $sqlAge .= "and DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between 30 and 39";
                }
            }

            if($criteria_40_49){
                if($criteria_14_19 || $criteria_20_29 || $criteria_30_39){
                    $sqlAge .= "or DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between 40 and 49";
                }else{
                    $sqlAge .= "and DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 between 40 and 49";
                }
            }

            if($criteria_50){
                if($criteria_14_19 || $criteria_20_29 || $criteria_30_39){
                    $sqlAge .= "or DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 > 50";
                }else{
                    $sqlAge .= "and DATEDIFF(CURRENT_DATE, STR_TO_DATE(birthday, '%Y-%m-%d'))/365 > 50";
                }
            }

            //Location
            $sqlLocation = "";
            $criteria_province = json_decode($_POST['criteria_province']);
            $criteria_hcm = json_decode($_POST['criteria_hcm']);
            $criteria_hanoi = json_decode($_POST['criteria_hanoi']);
            if(!$criteria_province){
                if($criteria_hcm && $criteria_hanoi){
                    $sqlLocation = "and pid = 1 or pid = 2";
                }else{
                    if($criteria_hcm) {
                        $sqlLocation = "and pid = 1";
                    }else if($criteria_hanoi){
                        $sqlLocation = "and pid = 2";
                    }
                }
            }

            //House size
            $sqlHouseSize = "";
            $criteria_single = json_decode($_POST['criteria_single']);
            $criteria_married = json_decode($_POST['criteria_married']);
            $criteria_1_child = json_decode($_POST['criteria_1_child']);
            $criteria_2_child = json_decode($_POST['criteria_2_child']);
            if($criteria_single){
                $sqlHouseSize = "and maried_status = 0";
            }

            if($criteria_married){
                if($criteria_single){
                    $sqlHouseSize .= "or maried_status = 1";
                }else{
                    $sqlHouseSize .= "and maried_status = 1";
                }
            }

            if($criteria_1_child){
                if($criteria_single || $criteria_married){
                    $sqlHouseSize .= "or children = 1";
                }else{
                    $sqlHouseSize .= "and children = 1";
                }
            }

            if($criteria_2_child){
                if($criteria_single || $criteria_married || $criteria_1_child){
                    $sqlHouseSize .= "or children = 2";
                }else{
                    $sqlHouseSize .= "children = 2";
                }
            }

            $sqlBuzzer = "1 = 1 ". $sqlGender . $sqlAge . $sqlLocation . $sqlHouseSize;

            $data = $this->model_management->getBuzzer($sqlBuzzer);
            echo json_encode(array("status"=>"ok", 'data'=>$data));
        }else{
            echo json_encode(array("status"=>"error"));
        }*/
    }

    public function saveSurveyChild(){
        if(isset($_POST['survey_child_title'])){
            $sid = $_POST['sid'];
            $survey_child_title = $_POST['survey_child_title'];
            $today = date("Y-m-d H:i:s");
            $returnId = $this->model_management->addSurveyChild($sid, $survey_child_title, "", $today, $today, 0);
            if($returnId){
                echo json_encode(array("status"=>"ok", 'scid'=>$returnId));
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function getSurveyId($sid){
        $survey_exists= $this->model_management->getSurveyById($sid);
        if($survey_exists){
            $id= $this->randomChars(6, '123456789');
            $this->getSurveyId($id);
        }

        return $sid;
    }

    public function updateSurvey(){

    }

    public function removeSurveyChild(){
        if(isset($_POST['scid'])){
            $scid = $_POST['scid'];
            $survey =$this->model_management->removeSurveyChildById($scid);
            $arrQuestion = $this->model_management->getQuestionParentBySid($scid);
            foreach($arrQuestion as $value){
                $this->model_management->removeQuestionChildByQid($value['qid']);
            }
            $this->model_management->removeQuestionByScid($scid);

            echo json_encode(array("status"=>"ok"));
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function saveQuestionSingle(){
        if(isset($_POST['question_title'])){
            $scid = $_POST['scid'];
            $question_title = $_POST['question_title'];
            $question_type = $_POST['question_type'];
            $answer = $_POST['answer'];
            $position = $_POST['position'];

            $qid = $this->model_management->addQuestion(0, $scid, $question_type, $question_title, $position, 0);
            if($qid){
                for($i = 0; $i < sizeof($answer); $i++){
                    $sub_title = $answer[$i];
                    $this->model_management->addQuestion($qid, 0, 0, $sub_title, $i, 0);
                }
                echo json_encode(array("status"=>"ok"));
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function saveQuestionMultiple(){
        if(isset($_POST['question_title'])){
            $scid = $_POST['scid'];
            $question_title = $_POST['question_title'];
            $question_type = $_POST['question_type'];
            $answer = $_POST['answer'];
            $position = $_POST['position'];
            $qid = $this->model_management->addQuestion(0, $scid, $question_type, $question_title, $position, 0);
            if($qid){
                for($i = 0; $i < sizeof($answer); $i++){
                    $sub_title = $answer[$i];
                    $this->model_management->addQuestion($qid, 0, 0, $sub_title, $i, 0);
                }
                echo json_encode(array("status"=>"ok"));
            }else{
                echo json_encode(array("status"=>"error"));
            }

        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function saveQuestionTable(){
        if(isset($_POST['question_title'])){
            $scid = $_POST['scid'];
            $question_title = $_POST['question_title'];
            $question_type = $_POST['question_type'];
            $answerRow = $_POST['answerRow'];
            $answerColumn = $_POST['answerColumn'];
            $position = $_POST['position'];
            $qid = $this->model_management->addQuestion(0, $scid, $question_type, $question_title, $position, 0);
            if($qid){
                for($i = 0; $i < sizeof($answerRow); $i++){
                    $sub_title = $answerRow[$i];
                    $this->model_management->addQuestion($qid, 0, 0, $sub_title, $i, 0);
                }
                for($j = 0; $j < sizeof($answerColumn); $j++){
                    $sub_title = $answerColumn[$j];
                    $this->model_management->addQuestionChild($qid, $sub_title, $j);
                }
                echo json_encode(array("status"=>"ok"));
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function getCampaign(){
        $campaign = $this->model_management->getCampaigns();
        $this->data['campaign'] = $campaign;
        $this->view->render("management/campaign", $this->data);
    }

    public function getCreateCampaign(){

        //Tag attribute
        $attributes = $this->model_management->getAttributeByParent(0);
        $this->data['attributes'] = $attributes;

        //Province
        $province = $this->model_management->getProvince();
        $this->data['province'] = $province;
        $this->view->render("management/campaign_create", $this->data);
    }

    public function getCriteria(){
        if(isset($_POST['atid'])){
            $atid = $_POST['atid'];
            $attribute = $this->model_management->getAttributeById($atid);
            $data = $this->model_management->getAttributeByParent($atid);
            if($data){
                for($i = 0; $i < sizeof($data); $i++){
                    $id = $data[$i]['atid'];
                    $children = $this->model_management->getAttributeByParent($id);
                    if($children){
                        $data[$i]['children'] = "1";
                    }
                }
            }
            $this->data['criteria_title'] = $attribute[0]['attr_name'];
            $this->data['data'] = $data;
            $this->data['atid'] = $atid;
            $this->view->render("management/campaign_criteria", $this->data);
        }
    }

    public function getCriteriaChildren(){
        if(isset($_POST['atid'])){
            $atid = $_POST['atid'];
            $attribute = $this->model_management->getAttributeById($atid);
            $data = $this->model_management->getAttributeByParent($atid);
            if($data){
                for($i = 0; $i < sizeof($data); $i++){
                    $id = $data[$i]['atid'];
                    $children = $this->model_management->getAttributeByParent($id);
                    if($children){
                        $data[$i]['children'] = "1";
                    }
                    $data[$i]['parent_title'] = $attribute[0]['attr_name'];
                }
                echo json_encode(array("status"=>"ok", "data"=>$data));
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function getCriteriaParent(){
        if(isset($_POST['atid'])){
            $atid = $_POST['atid'];
            $data = $this->model_management->getAttributeById($atid);
            if($data){
                $sub = $this->model_management->getAttributeById($data[0]['attr_parent']);
                if($sub && $sub[0]['attr_parent'] != 0){
                    $title = $sub[0]['attr_name'];
                    echo json_encode(array("status"=>"ok", "title"=>$title));
                }else{
                    echo json_encode(array("status"=>"error"));
                }
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function getSurvey(){
        $data = $this->model_management->getSurveyChild();
        $survey = $this->model_management->getSurvey();
        $this->data['data'] = $data;
        $this->data['survey'] = $survey;
        $this->view->render("management/survey", $this->data);
    }

    public function getSurveyBuilder(){
        $this->view->render("management/builder/builder", $this->data);
    }

    public function getCreateSurvey(){
        $folder = $this->model_management->getSurvey();
        $this->data['folder'] = $folder;
        $this->view->render("management/survey_create", $this->data);
    }

    public function getEditSurvey(){
        if(isset($_POST['sid'])){
            $scid = $_POST['sid'];
            $survey_child = $this->model_management->getSurveyChildById($scid);
            if($survey_child){
                $folder = $this->model_management->getSurvey();

                //variable
                $sid = 0;
                $survey_child_title = "";
                foreach($survey_child as $value){
                    $sid = $value['sid'];
                    $survey_child_title = $value['survey_child_name'];
                }

                //get question from survey
                $question = $this->model_management->getQuestionParentBySidAsc($scid);
                for($i = 0; $i < sizeof($question); $i++){
                    $parent = $question[$i]['qid'];
                    $type = $question[$i]['question_type'];

                    //get attribute and add into question
                    $questionAttribute = $this->model_management->getQuestionAttributeByQid($question[$i]['qid']);
                    if($questionAttribute){
                        $tag = array();
                        foreach($questionAttribute as $value){
                            $attribute = $this->model_management->getAttributeById($value['atid']);
                            $title = $attribute[0]['attr_name'];
                            $tag = ['id'=>$value['atid'], 'title'=>$title];
                        }
                        $question[$i]['tag'] = $tag;
                    }

                    if($type == 3){
                        $row = $this->model_management->getQuestionByParentId($parent);
                        $column = $this->model_management->getQuestionChildByQid($parent);
                        $question[$i]['row'] = $row;
                        $question[$i]['column'] = $column;
                        //table
                    }else{
                        $children = $this->model_management->getQuestionByParentId($parent);
                        if($children){
                            for($j = 0; $j < sizeof($children); $j++){
                                //get attribute and add into question
                                $questionAttribute = $this->model_management->getQuestionAttributeByQid($children[$i]['qid']);
                                if($questionAttribute){
                                    $tag = array();
                                    foreach($questionAttribute as $value){
                                        $attribute = $this->model_management->getAttributeById($value['atid']);
                                        $title = $attribute[0]['attr_name'];
                                        $tag = ['id'=>$value['atid'], 'title'=>$title];
                                    }
                                    $children[$j]['tag'] = $tag;
                                }
                            }
                            $question[$i]['children'] = $children;
                        }
                    }



                }

                //get tag
                $tag = $this->model_management->getAttributeTag();
                $this->data['tag'] = $tag;

                $this->data['folder'] =  $folder;
                $this->data['sid'] = $sid;
                $this->data['scid'] = $scid;
                $this->data['survey_child_title'] = $survey_child_title;
                $this->data['question'] = $question;
                $this->view->render("management/survey_edit", $this->data);
            }else{
                echo '<p>Trang này không tồn tại.</p>';
            }
        }else{

        }
    }

    public function addTag(){
        if(isset($_POST['qid'])){
            $qid = $_POST['qid'];
            $tid = $_POST['tid'];
            $this->model_management->addQuestionAttribute($qid, $tid);
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function getSurveyAnalytics(){
        if(isset($_POST['sid'])){
            $sid = $_POST['sid'];
            //Thông tin survey
            $survey = $this->model_management->getSurveyChildById($sid);
            //Lấy tất cả các câu hỏi từ survey.
            $question = $this->model_management->getQuestionByScid($sid);
            for($i = 0; $i < sizeof($question); $i++){
                //Đếm tổng số user đã trả lời câu hỏi
                $numberAns = $this->model_management->getNumberAnsweredOfQuestion($question[$i]['qid']);
                if($numberAns){
                    $question[$i]['total'] = $numberAns[0]['number'];
                }

                switch($question[$i]['question_type']){
                    case "1":{
                        //Nếu câu hỏi kiểu choose
                        //Lấy các câu trả lời của câu hỏi
                        $question_child = $this->model_management->getQuestionByParentId($question[$i]['qid']);
                        if($question_child){
                            for($j = 0; $j < sizeof($question_child); $j++){
                                $qid = $question_child[$j]['parent_qid'];
                                $ans = $question_child[$j]['qid'];
                                //Lấy số lượng trả lời của user với câu trả lời
                                $number = $this->model_management->getQuestionAnswered($qid, $ans);
                                if($number){
                                    $question_child[$j]['number'] = $number[0]['number'];
                                }
                            }
                            $question[$i]['children'] = $question_child;
                        }
                        break;
                    }
                    case "2":{
                        //Nếu câu hỏi kiểu multi choose
                        $question_child = $this->model_management->getQuestionByParentId($question[$i]['qid']);
                        if($question_child){
                            for($j = 0; $j < sizeof($question_child); $j++){
                                $qid = $question_child[$j]['parent_qid'];
                                $ans = $question_child[$j]['qid'];
                                //Lấy số lượng trả lời của user với câu trả lời
                                $number = $this->model_management->getQuestionAnsweredMultiChoose($qid, $ans);
                                if($number){
                                    $question_child[$j]['number'] = $number[0]['number'];
                                }
                            }
                            $question[$i]['children'] = $question_child;
                        }
                        break;
                    }
                    case "3":{
                        //Nếu câu hỏi kiểu table
                        $question_rows = $this->model_management->getQuestionByParentId($question[$i]['qid']);
                        $question_columns = $this->model_management->getQuestionChildByQid($question[$i]['qid']);
                        if($question_rows && $question_columns){
                            //for($m = 0; $m < sizeof($question_rows); $m++){
                                //$rowValue = $question_rows[$m]['qid'];
                                $column = array();
                                for($n = 0; $n < sizeof($question_columns); $n++){
                                    $columnValue = $question_columns[$n]['qcid'];

                                    $column[$n]['name'] = $question_columns[$n]['question_child_name'];
                                    $data = array();
                                    for($k = 0; $k < sizeof($question_rows); $k++){
                                        $rowValue = $question_rows[$k]['qid'];
                                        $number = $this->model_management->getQuestionAnsweredTable($question[$i]['qid'], $rowValue, $columnValue);
                                        if($number){
                                            $data[] = intval($number[0]['number']);
                                        }else{
                                            $data[] = 0;
                                        }
                                    }

                                    $column[$n]['data'] = $data;
                                }
                            //}
                            $question[$i]['ans'] = $column;
                            $question[$i]['rows'] = $question_rows;
                            $question[$i]['columns'] = $question_columns;
                        }
                        break;
                    }

                }



            }

            //Các câu hỏi của survey đã được trả lời.




            /*$user_survey = $this->model_management->getUserSurveyByScid($sid);
            $totalUserSurvey = sizeof($user_survey); //Tổng số user khảo sát
            $arrQuestion = array();
            foreach($user_survey as $value){
                $answers = $this->model_management->getAnsweredByUsid($value['usid']);
                foreach($answers as $v){
                    $answersQid = $v['qid'];
                    $getQuestion =  $this->model_management->getQuestionById($answersQid);
                    //Count number qid

                    if($getQuestion){
                        //Số lượng người khảo sát/câu hỏi
                        $numberUserQuestion = 0;
                        if($this->numberInArray($answersQid, $arrQuestion)){
                            $numberUserQuestion++;
                        }else{
                            $arrQuestion[] = $answersQid;
                        }
                    }
                }
            }*/
            $this->data['survey'] = $survey;
            $this->data['question'] = $question;
            $this->view->render("management/survey_analytics", $this->data);
        }
    }

    public function numberInArray($x, $y){
        $ok = false;
        for($i = 0; $i < sizeof($y); $i++){
            if($x == $y[$i]){
                $ok = true;
            }
        }
        return $ok;
    }

    public function getSurveyPosition(){
        if(isset($_POST['sid'])){
            $sid = $_POST['sid'];
            $surveyParent = $this->model_management->getSurveyById($sid);
            $survey = $this->model_management->getSurveyChildBySid($sid);
            $this->data['title'] = $surveyParent[0]['survey_name'];
            $this->data['survey'] = $survey;
            $this->view->render("management/survey_position", $this->data);
        }
    }

    public function updatePositionSurvey(){
        if(isset($_POST['sid'])){
            $sid = $_POST['sid'];
            $position = $_POST['position'];
            $this->model_management->updateSurveyChildPosition($sid, $position);
            echo json_encode(array('status' => "ok"));
        }else{
            echo json_encode(array('status' => "error"));
        }
    }

    public function getAttributes(){
        $this->view->render("management/attributes", $this->data);
    }

    public function getAttributeTree(){
        if(isset($_POST['aid'])){
            $aid = $_POST['aid'];
            $data = $this->model_management->getAttributeByParent($aid);
            echo json_encode(array('status' => "ok", 'data'=>$data));
        }else{
            echo json_encode(array('status' => "error"));
        }
    }

    public function addAttribute(){
        if(isset($_POST['aid'])){
            $aid = $_POST['aid'];
            $attr_name = "New folder";
            $attr_position = 0;
            $attr_tag = 1;
            $attr_type  = "folder";
            $atid = $this->model_management->addAttribute($attr_name, $attr_position, $aid, $attr_tag, $attr_type);
            echo json_encode(array('status' => "ok", 'atid'=>$atid));
        }else{
            echo json_encode(array('status' => "error"));
        }
    }

    public function updateAttribute(){
        if(isset($_POST['aid'])){
            $aid = $_POST['aid'];
            $name = $_POST['name'];
            $this->model_management->updateAttributeName($aid, $name);
            echo json_encode(array('status' => "ok"));
        }else{
            echo json_encode(array('status' => "error"));
        }
    }

    public function deleteAttribute(){
        if(isset($_POST['aid'])){
            $aid = $_POST['aid'];
            $this->model_management->deleteAttribute($aid);
            //Delete children node
            $data = $this->model_management->getAttributeByParent($aid);
            if($data){
                foreach($data as $value){
                    $atid = $value['atid'];
                    $this->model_management->deleteAttribute($atid);
                }
            }

            echo json_encode(array('status' => "ok"));
        }else{
            echo json_encode(array('status' => "error"));
        }
    }

    public function getAttributesTree(){
        require_once(ROOT_PATH . 'public/tag/class.db.php');
        require_once(ROOT_PATH . 'public/tag/class.tree.php');
        if(isset($_GET['operation'])) {
            $fs = new tree(db::get('mysqli://root@127.0.0.1/buzzy'), array('structure_table' => 'attributes_struct', 'data_table' => 'attributes_data', 'data' => array('nm')));
            try {
                $rslt = null;
                switch($_GET['operation']) {
                    case 'analyze':
                        var_dump($fs->analyze(true));
                        die();
                        break;
                    case 'get_node':
                        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
                        $temp = $fs->get_children($node);
                        $rslt = array();
                        foreach($temp as $v) {
                            $rslt[] = array('id' => $v['id'], 'text' => $v['nm'], 'children' => ($v['rgt'] - $v['lft'] > 1));
                        }
                        break;
                    case "get_content":
                        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? $_GET['id'] : 0;
                        $node = explode(':', $node);
                        if(count($node) > 1) {
                            $rslt = array('content' => 'Multiple selected');
                        }
                        else {
                            $temp = $fs->get_node((int)$node[0], array('with_path' => true));
                            $rslt = array('content' => 'Selected: /' . implode('/',array_map(function ($v) { return $v['nm']; }, $temp['path'])). '/'.$temp['nm']);
                        }
                        break;
                    case 'create_node':
                        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
                        $temp = $fs->mk($node, isset($_GET['position']) ? (int)$_GET['position'] : 0, array('nm' => isset($_GET['text']) ? $_GET['text'] : 'New node'));
                        $rslt = array('id' => $temp);
                        break;
                    case 'rename_node':
                        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
                        $rslt = $fs->rn($node, array('nm' => isset($_GET['text']) ? $_GET['text'] : 'Renamed node'));
                        break;
                    case 'delete_node':
                        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
                        $rslt = $fs->rm($node);
                        break;
                    case 'move_node':
                        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
                        $parn = isset($_GET['parent']) && $_GET['parent'] !== '#' ? (int)$_GET['parent'] : 0;
                        $rslt = $fs->mv($node, $parn, isset($_GET['position']) ? (int)$_GET['position'] : 0);
                        break;
                    case 'copy_node':
                        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
                        $parn = isset($_GET['parent']) && $_GET['parent'] !== '#' ? (int)$_GET['parent'] : 0;
                        $rslt = $fs->cp($node, $parn, isset($_GET['position']) ? (int)$_GET['position'] : 0);
                        break;
                    default:
                        throw new Exception('Unsupported operation: ' . $_GET['operation']);
                        break;
                }
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode($rslt);
            }
            catch (Exception $e) {
                header($_SERVER["SERVER_PROTOCOL"] . ' 500 Server Error');
                header('Status:  500 Server Error');
                echo $e->getMessage();
            }
            die();
        }
    }

    public function getGroup(){
        $this->view->render("management/groups", $this->data);
    }

    public function getPermission(){
        $this->view->render("management/permission", $this->data);
    }

    //Question
    public function getBuilderChoice(){
        //get tag
        $tag = $this->model_management->getAttributeTag();
        $this->data['tag'] = $tag;
        $this->view->render("management/builder/choice", $this->data);
    }

    public function getBuilderMultiChoice(){
        //get tag
        $tag = $this->model_management->getAttributeTag();
        $this->data['tag'] = $tag;
        $this->view->render("management/builder/multiple_choice", $this->data);
    }

    public function getBuilderTable(){
        //get tag
        $tag = $this->model_management->getAttributeTag();
        $this->data['tag'] = $tag;
        $this->view->render("management/builder/table", $this->data);
    }

    public function uploadImage(){
        $image = new SimpleImage();
        $output = ROOT_PATH."upload/images/";
        if (isset($_FILES["myfile"])) {
            $ret = array();
            $fileName = "";
            $error = $_FILES["myfile"]["error"];
            $mid = 0;
            {
                $sid = $image->randomChars(6, '123456789');
                if (!is_array($_FILES["myfile"]['name'])) //single file
                {
                    $fileName = $sid."-".$_FILES["myfile"]["name"];
                    move_uploaded_file($_FILES["myfile"]["tmp_name"], $output.$fileName);
                    $image->load($output . $fileName);
                    $image->resizeImage(700,500);
                    //Small image
                    copy($output . $fileName, $output . 'small/'. $fileName);
                    $image->load($output . 'small/'. $fileName);
                    $image->resizeImage(300,182);

                    //Add image into database
                    $uid = Session::get("uid");
                    $name = $fileName;
                    $title = "";
                    $caption = "";
                    $alt = "";
                    $description = "";
                    $date = date('Y-m-d H:i:s');
                    if($uid){
                        $mid = $this->model_management->addImages($uid, 0, 0, 0, 1, $name, $title, $date, $caption, $alt, $description);
                    }

                    $ret[$fileName] = $output . $sid."-".$fileName;
                } else {
                    $fileCount = count($_FILES["myfile"]['name']);
                    for ($i = 0; $i < $fileCount; $i++) {
                        $fileName = $sid."-".$_FILES["myfile"]["name"][$i];
                        $ret[$fileName] = $output . $fileName;
                        move_uploaded_file($_FILES["myfile"]["tmp_name"][$i], $output . $fileName);
                        $image->load($output . $fileName);
                        $image->resizeImage(700,500);
                        //Small image
                        copy($output . $fileName, $output . 'small/'. $fileName);
                        $image->load($output . 'small/'. $fileName);
                        $image->resizeImage(300,182);

                        //Add image into database
                        $uid = Session::get("uid");
                        $name = $fileName;
                        $title = "";
                        $caption = "";
                        $alt = "";
                        $description = "";
                        $date = date('Y-m-d H:i:s');
                        if($uid){
                            $mid = $this->model_management->addImages($uid, 0, 0, 0, 1, $name, $title, $date, $caption, $alt, $description);
                        }
                    }
                }
            }
            echo json_encode($mid);
        }else{
            echo json_encode(array('status' => "error"));
        }
    }

    public function removeImages(){
        if(isset($_POST['mid'])){
            $mid = $_POST['mid'];
            //Remove image in folder
            $data = $this->model_management->getImageById($mid);
            if($data){
                $name = "";
                foreach($data as $value){
                    $name = $value['media_name'];
                }
                unlink(ROOT_PATH."upload/images/".$name."");
                unlink(ROOT_PATH."upload/images/small/".$name."");

                $this->model_management->removeImage($mid);

                echo json_encode(array('status' => "ok"));
            }else{
                echo json_encode(array('status' => "error"));
            }
        }else{
            echo json_encode(array('status' => "error"));
        }
    }

    /*function randomChars($length,$pattern="23456789abcdefghijkmnpqrstuvwxyz")
    {
        $patternlength = strlen($pattern)-1;
        $key = '';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,$patternlength)};
        }
        return $key;
    }*/

}

class SimpleImage {

    var $image;
    var $image_type;
    var $url;

    function load($filename) {
        $this->url = $filename;
        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];
        if( $this->image_type == IMAGETYPE_JPEG ) {

            $this->image = imagecreatefromjpeg($filename);
        } elseif( $this->image_type == IMAGETYPE_GIF ) {

            $this->image = imagecreatefromgif($filename);
        } elseif( $this->image_type == IMAGETYPE_PNG ) {

            $this->image = imagecreatefrompng($filename);
        }
    }

    function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {

        if( $image_type == IMAGETYPE_JPEG ) {
            imagejpeg($this->image,$filename,$compression);
        } else if( $image_type == IMAGETYPE_GIF ) {

            imagegif($this->image,$filename);
        } else if( $image_type == IMAGETYPE_PNG ) {

            imagepng($this->image,$filename);
        }
        if( $permissions != null) {

            chmod($filename,$permissions);
        }
    }

    function output($image_type=IMAGETYPE_JPEG) {

        if( $image_type == IMAGETYPE_JPEG ) {
            imagejpeg($this->image);
        } elseif( $image_type == IMAGETYPE_GIF ) {

            imagegif($this->image);
        } elseif( $image_type == IMAGETYPE_PNG ) {

            imagepng($this->image);
        }
    }

    function getWidth() {

        return imagesx($this->image);
    }

    function getHeight() {

        return imagesy($this->image);
    }

    function resizeToHeight($height) {

        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        $this->resize($width,$height);
    }

    function resizeToWidth($width) {
        $ratio = $width / $this->getWidth();
        $height = $this->getheight() * $ratio;
        $this->resize($width,$height);
    }

    function scale($scale) {
        $width = $this->getWidth() * $scale/100;
        $height = $this->getheight() * $scale/100;
        $this->resize($width,$height);
    }

    function resize($width,$height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }

    function resizeImage($width,$height){
        if($this->getWidth() > $width && $this->getHeight() > $height){
            $ratio = $width / $this->getWidth();
            $height = $this->getheight() * $ratio;
            $this->resize($width, $height);
            $this->save($this->url);
        }else if($this->getWidth() > $width && $this->getHeight() < $height){
            $this->resizeToWidth($width);
            $this->save($this->url);
        }else if($this->getWidth() < $width && $this->getHeight() > $height){
            $this->resizeToHeight($height);
            $this->save($this->url);
        }
    }

    function randomChars($length,$pattern="23456789abcdefghijkmnpqrstuvwxyz")
    {
        $patternlength = strlen($pattern)-1;
        $key = '';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,$patternlength)};
        }
        return $key;
    }
}
?>